import re
from rest_framework import serializers
from .models import User,Address
from django_redis import get_redis_connection
from rest_framework_jwt.settings import api_settings

########################################### 以下内容：注册 序列化器（反序列化）##########################################################
class RegisterCreateSerializer(serializers.ModelSerializer):
    password2 = serializers.CharField(label='确认密码', write_only=True, allow_null=False, allow_blank=False)
    sms_code = serializers.CharField(label='短信验证码', max_length=6, min_length=6, write_only=True, allow_null=False,
                                     allow_blank=False)
    allow = serializers.CharField(label='同意协议', write_only=True, allow_null=False, allow_blank=False)
    token = serializers.CharField(label='JWT用token',read_only=True)
    class Meta:
        model = User
        fields = ('id', 'username', 'password', 'mobile', 'password2', 'sms_code', 'allow','token')
        extra_kwargs = {
            'id': {'read_only': True},
            'username': {
                'min_length': 5,
                'max_length': 20,
                'error_messages': {
                    'min_length': '仅允许5-20个字符的用户名',
                    'max_length': '仅允许5-20个字符的用户名',
                }
            },
            'password': {
                'write_only': True,
                'min_length': 8,
                'max_length': 20,
                'error_messages': {
                    'min_length': '仅允许8-20个字符的密码',
                    'max_length': '仅允许8-20个字符的密码',
                }
            }
        }
    #密码、手机号、短信验证码、协议
    def validate_mobile(self,value):

        if not re.match(r'1[345789]\d{9}',value):
            raise serializers.ValidationError('手机号格式错误')
        return value


    def validate_allow(self,value):

        if value != 'true':
            raise serializers.ValidationError('尚未同意用户协议')
        return value


    def validate(self, attrs):

        if attrs['password'] !=attrs['password2']:
            raise serializers.ValidationError('两次密码输入不一致')

        redis = get_redis_connection('code')
        sms_code = redis.get('sms_%s'%attrs['mobile'])

        if sms_code is None:
            raise serializers.ValidationError('验证码已过期')

        if sms_code.decode() != attrs['sms_code']:
            raise serializers.ValidationError('短信验证码错误')

        return attrs

    def create(self, validated_data):

        del validated_data['password2']
        del validated_data['sms_code']
        del validated_data['allow']

        user = super().create(validated_data)
        user.set_password(validated_data['password'])
        user.save()

        #生成token返回给浏览器
        jwt_payload_handler = api_settings.JWT_PAYLOAD_HANDLER
        jwt_encode_handler = api_settings.JWT_ENCODE_HANDLER
        payload = jwt_payload_handler(user)
        token = jwt_encode_handler(payload)
        user.token = token

        return user


########################################### 以下内容：个人中心 序列化器（序列化）##########################################################
class UserCenterInfoSerializer(serializers.ModelSerializer):

    class Meta:
        model = User
        fields = ['username','mobile','email','email_active']


########################################### 以下内容：设置邮箱  序列化器（反序列化）##########################################################
from celery_tasks.email.tasks import send_verificate_email
class UserEmailSerializer(serializers.ModelSerializer):
    class Meta:
        model = User
        fields = ['email']
        extra_kwargs = {
            'email':{
                'required': True
            }
        }

    def update(self, instance, validated_data):
        #将邮箱保存到数据库
        email = validated_data.get('email')
        instance.email = email
        instance.save()


        #向该邮箱发送邮箱验证邮件
        # send_verificate_email(email,instance.id)
        send_verificate_email.delay(email,instance.id)

        return instance



########################################### 以下内容：收货地址  序列化器（反序列化）##########################################################

class AddressAddSerializer(serializers.ModelSerializer):
    province = serializers.StringRelatedField(read_only=True)
    city = serializers.StringRelatedField(read_only=True)
    district = serializers.StringRelatedField(read_only=True)
    province_id = serializers.IntegerField(required=True,label='省ID')
    city_id = serializers.IntegerField(required=True,label='市ID')
    district_id = serializers.IntegerField(required=True,label='县ID')
    mobile = serializers.RegexField(required=True,regex=r'1[345789]\d{9}',label='手机号')

    class Meta:
        model = Address
        exclude = ['user','is_deleted','update_time','create_time']

    def create(self, validated_data):
        user = self.context['request'].user
        validated_data['user_id'] = user.id

        return super().create(validated_data)